package com.yaoge.mvc.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.UUID;

/**
 * 用来测试 上传文件和下载文件
 */
@Controller
@RequestMapping("/file")
public class TestFile {

    @RequestMapping("/testDown")
    public ResponseEntity<byte[]> testDown(HttpSession session) throws IOException {

        ServletContext servletContext = session.getServletContext();

        //获取真实地址
        String realPath = servletContext.getRealPath("/static/img/1.png");

        InputStream is=new FileInputStream(realPath);

        byte[] bytes = new byte[is.available()];

        is.read(bytes);

        MultiValueMap<String,String> httpHeaders = new HttpHeaders();

        httpHeaders.add("Content-Disposition","attachment;filename=1.jpg");

        HttpStatus status=HttpStatus.OK;

        ResponseEntity<byte[]> responseEntity=new ResponseEntity<byte[]>(bytes,httpHeaders,status);
        is.close();
        return responseEntity;
    }

    @RequestMapping("/testUp")
    public String testUp(MultipartFile photo,HttpSession session) throws IOException {
        String filename = photo.getOriginalFilename();

        String substring = filename.substring(filename.lastIndexOf("."));

        filename= UUID.randomUUID().toString()+substring;

        ServletContext servletContext = session.getServletContext();

        String img = servletContext.getRealPath("img");

        File file = new File(img);

        if (!file.exists()){
            file.mkdir();
        }
        String finalPath=img+File.separator+filename;

        photo.transferTo(new File(finalPath));

        return "success";
    }
}
